package com.jarvis.hospital.util;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

/**
 * Created by jarvis.liu on 6/19/2017.
 */

public class UpdateManager {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 下载失败 */
    private static final int DOWNLOAD_FAIL = 3;
    /* 保存解析的XML信息 */
    HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;

   // private ApiService service;
    private String load_url = "";

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 取消下载对话框显示
                    mDownloadDialog.dismiss();
                    // 安装文件
                    installApk();
                    break;
                case DOWNLOAD_FAIL:
                    // 安装文件
                    // 取消下载对话框显示
                    deleteFile();
                    mDownloadDialog.dismiss();
                    Toast.makeText(mContext, "下载失败", Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context) {
//        this.mContext = context;
//        service = RequestApi.create(ApiService.class);
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
//    public void checkUpdate() {
//        // 获取当前软件版本
//        int versionCode = VersionManager.getVersionCode(mContext);
//        RequestUpdateModel model = new RequestUpdateModel("getUpdateInfo");
//        model.setVersionCode(versionCode + "");
//        Call<ResponseData<UpdateModel>> call = service.update(model);
//        call.enqueue(new Callback<ResponseData<UpdateModel>>() {
//            @Override
//            public void onResponse(Call<ResponseData<UpdateModel>> call, Response<ResponseData<UpdateModel>> response) {
//                if (response.body() != null) {
//                    int statusCode = response.body().getStatusCode();
//                    int resultCode = response.body().getResultCode();
//                    if (statusCode == 200 && resultCode == 100) {
//                        load_url = response.body().getData().getPath();
//                        showNoticeDialog();
//                    } else if (statusCode == 200 && resultCode == 200) {
//
//                    } else {
//                        Toast.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
//                    }
//                } else {
//                    Toast.makeText(mContext, "请求失败", Toast.LENGTH_LONG).show();
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ResponseData<UpdateModel>> call, Throwable t) {
//                Toast.makeText(mContext, RequestApi.detailError(t), Toast.LENGTH_LONG).show();
//            }
//        });
//    }

    /**
     * 显示软件更新对话框
     */
    public void showNoticeDialog() {
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("软件更新");
        builder.setMessage("发现新版本");
        // 更新
        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 显示下载对话框
               // showDownloadDialog();
            }
        });
        // 稍后更新
        builder.setNegativeButton("稍候再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 显示软件下载对话框
     */
/*    private void showDownloadDialog() {
        // 构造软件下载对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("更新中");
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dia_update, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;

                deleteFile();
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.setCancelable(false);
        mDownloadDialog.show();
        // 现在文件
        //downloadApk();
        RxPermissions.getInstance(mContext)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        downLoadApk();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
                                    }
                                }
                            }.start();
                        } else {
                            mDownloadDialog.dismiss();
                            Toast.makeText(mContext, "请选择允许使用权限", Toast.LENGTH_LONG).show();
                        }
                    }
                });

    }*/

    private void deleteFile() {
        // 获得存储卡的路径
        String sdpath = Environment.getExternalStorageDirectory() + "/";
        mSavePath = sdpath + "pbb/";
        File file = new File(mSavePath + "pbb.apk");
        if (file.isFile() && file.exists()) {
            file.delete();
        }
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    private void downLoadApk() throws Exception {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 获得存储卡的路径
            String sdpath = Environment.getExternalStorageDirectory() + "/";
            mSavePath = sdpath + "pbb/";
            URL url = new URL(load_url);
            // 创建连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            // 获取文件大小
            int length = conn.getContentLength();
            // 创建输入流
            InputStream is = conn.getInputStream();

            File file = new File(mSavePath);
            // 判断文件目录是否存在
            if (!file.exists()) {
                file.mkdir();
            }
            File apkFile = new File(mSavePath, "pbb.apk");
            FileOutputStream fos = new FileOutputStream(apkFile);
            int count = 0;
            // 缓存
            byte buf[] = new byte[1024];
            // 写入到文件中
            do {
                int numread = is.read(buf);
                count += numread;
                // 计算进度条位置
                progress = (int) (((float) count / length) * 100);
                // 更新进度
                mHandler.sendEmptyMessage(DOWNLOAD);
                if (numread <= 0) {
                    // 下载完成
                    mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                    break;
                }
                // 写入文件
                fos.write(buf, 0, numread);
            } while (!cancelUpdate);// 点击取消就停止下载.
            fos.close();
            is.close();
        }
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(mHashMap.get("url"));
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, mHashMap.get("name"));
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, "pbb.apk");
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
}
